import { useRoutes, useNavigate, useLocation } from "react-router-dom"

import Layout from "@/pages/layout/index.jsx";
import Login from "@/pages/login/index.jsx";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { getInfo } from "./store/actions";
import { generateRoutes } from "./store/modules/permission";
import { asyncRoutes } from "./pages";
import { useMemo } from "react";




//静态路由 ，没有权限的路由----------未放到pages/index
const arr = [
    { path: '/', element: <Layout />, children: [] },
    { path: '/Login', element: <Login />, children: [] }
]
// -----------------------------------------------------------

//白名单
const whiteList = ['/login']

function Page() {
    const { token, roles, accessRoutes } = useSelector(state => state.user)
    const dispatch = useDispatch();
    const navigator = useNavigate();
    const { pathname } = useLocation();

    //监听token变化
    useEffect(() => {
        //当tolen从无到有，有了token，才能获取用户信息
        if (token) {
            dispatch(getInfo())
        } else {
            navigator('/login', { replace: true })
        }

    }, [token])

    //roles和路由表，算法，生成当用户可以访问的路由规则
    useEffect(() => {
        if (roles && roles.length > 0) {
            dispatch(generateRoutes(asyncRoutes, roles))
        }

    }, [roles])
    //对应客户看不到商品管理/用户管理选项
    useEffect(() => {
        if (accessRoutes && accessRoutes.length > 0) {
            navigator('/dashboard', { replace: true })
        }
    }, [accessRoutes])

    useEffect(() => {
        // !whiteList.includes(pathname) 表示访问的路径并没有在白名单中
        // 如果在白名单中，是不需要token
        if (!whiteList.includes(pathname) && !token) {
            navigator("/login", { replace: true })
        }
        // 表示已经登录了，已经有token了，又访问登录页面
        if (token && pathname === "/login") {
            navigator("/", { replace: true })
        }
        if (token && pathname === "/") {
            navigator("/dashboard", { replace: true })
        }
    }, [pathname])





    //计算出全部的路由规则
    const routes = useMemo(() => {
        const result = [...arr]; //静态路由规则
        result[0].children = accessRoutes;
        return result;
    }, [accessRoutes])
    console.log('全部的路由规则', routes);


    const element = useRoutes(arr)
    return element;
}
export default Page;